package com.pdx.shiro.realm;

import com.pdx.service.SecurityService;
import com.pdx.service.impl.SecurityServiceImpl;
import com.pdx.utils.DigestsUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;
import java.util.Map;

/**
 * @author 派 大 星
 * @function
 * @date 2022/4/7 18:10
 * @website https://blog.csdn.net/Gaowumao
 */
public class CustomRealm extends AuthorizingRealm {

    public CustomRealm(){
        HashedCredentialsMatcher matcher =new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName(DigestsUtil.SHA1);
        matcher.setHashIterations(DigestsUtil.ITERATIONS);
        setCredentialsMatcher(matcher);
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String loginName = (String) principals.getPrimaryPrincipal();
        SecurityServiceImpl securityService = new SecurityServiceImpl();
        List<String> roles = securityService.findRoleByLoginName(loginName);
        List<String> permission = securityService.findPermissionByLoginName(loginName);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permission);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String loginName = (String) token.getPrincipal();
        SecurityServiceImpl securityService = new SecurityServiceImpl();
        Map<String, String> map = securityService.findPasswordByLoginName(loginName);
        if (map.isEmpty()){
            throw new UnknownAccountException("账户不存在");
        }
        String salt = map.get("salt");
        String password = map.get("password");
        return new SimpleAuthenticationInfo(loginName,password, ByteSource.Util.bytes(salt),getName());
    }
}
